package org.mx.service.server.jmx;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.mx.service.server.WebsocketServerConfigBean;

/**
 * Websocket服务器MXBean实现类
 * @author john.peng
 *
 */
public class WebsocketServer extends HttpServer implements WebsocketServerMXbean {
	private Set<String> paths;
	private Map<String, Long> sessionCounts, messageCounts, errorCounts;
	private final String sessionCountsLock = "Websocket session counts lock",
			messageCountsLock = "Websocket message counts lock", errorCountsLock = "Websocket error counts lock";

	/**
	 * 构造函数
	 * @param configBean Websocket服务器配置信息对象
	 */
	public WebsocketServer(WebsocketServerConfigBean configBean) {
		super(configBean);
		sessionCounts = new HashMap<>();
		messageCounts = new HashMap<>();
		errorCounts = new HashMap<>();
	}

	/**
	 * 指定路径的会话计数发生变化
	 * @param path websocket路径
	 * @param count 会话变化计数
	 */
	public void sessionChange(String path, long count) {
		synchronized (sessionCountsLock) {
			Long num = sessionCounts.get(path);
			if (num == null) {
				num = 0l;
			}
			sessionCounts.put(path, num + count);
		}
	}

	/**
	 * 指定路径消息计数发生变化
	 * @param path websocket路径
	 * @param count 消息变化计数
	 */
	public void messageChange(String path, long count) {
		synchronized (messageCountsLock) {
			Long num = messageCounts.get(path);
			if (num == null) {
				num = 0l;
			}
			messageCounts.put(path, num + count);
		}
	}
	
	/**
	 * 指定路径的错误计数发生变化
	 * @param path websocket路径
	 * @param count 错误变化计数
	 */
	public void errorChange(String path, long count) {
		synchronized (errorCountsLock) {
			Long num = errorCounts.get(path);
			if (num == null) {
				num = 0l;
			}
			errorCounts.put(path, num + count);
		}
	}

	@Override
	public Map<String, Long> getWebsocketSessionCounts() {
		return sessionCounts;
	}

	@Override
	public Map<String, Long> getWebsocketMessageCounts() {
		return messageCounts;
	}

	@Override
	public Map<String, Long> getWebsocketErrorCounts() {
		return errorCounts;
	}

	@Override
	public Set<String> getWebsocketServerPaths() {
		return paths;
	}

	/**
	 * 设置Websocket服务器监听的路径列表
	 * @param paths 监听的路径列表
	 */
	public void setWebsocketServerPaths(Set<String> paths) {
		this.paths = paths;
	}
}
